package com.zenithmind.coding.controller;

import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.coding.controller.base.BaseController;
import com.zenithmind.coding.pojo.dto.SubmissionDTO;
import com.zenithmind.coding.pojo.vo.SubmissionVO;
import com.zenithmind.coding.service.SubmissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 代码提交控制器 - 遵循单一职责原则，专门处理代码提交的基本操作
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Tag(name = "代码提交", description = "代码提交和评判相关接口")
@RestController
@RequestMapping("/api/zenithMind/v1/submissions")
@RequiredArgsConstructor
public class SubmissionController extends BaseController {

    private final SubmissionService submissionService;

    @Operation(summary = "提交代码", description = "提交代码进行评判")
    @PostMapping
    public Result<SubmissionVO> submitCode(@Valid @RequestBody SubmissionDTO submissionDTO) {
        SubmissionVO submission = submissionService.submitCode(submissionDTO);
        logOperation("提交代码", "问题ID: " + submissionDTO.getProblemId() + ", 语言: " + submissionDTO.getLanguage());
        return success(submission);
    }

    @Operation(summary = "分页查询提交记录", description = "分页查询代码提交记录")
    @GetMapping
    public Result<PageResult<SubmissionVO>> getSubmissionPage(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "问题ID") @RequestParam(required = false) String problemId,
            @Parameter(description = "编程语言") @RequestParam(required = false) String language,
            @Parameter(description = "提交状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        PageResult<SubmissionVO> result = submissionService.getSubmissionPage(current, size, userId, 
                                                                             problemId, language, status, startTime, endTime);
        return Result.success(result);
    }

    @Operation(summary = "查询提交详情", description = "根据ID查询代码提交详情")
    @GetMapping("/{id}")
    public Result<SubmissionVO> getSubmissionById(@Parameter(description = "提交ID") @PathVariable String id) {
        SubmissionVO submission = submissionService.getSubmissionById(id);
        return Result.success(submission);
    }

    @Operation(summary = "重新评判", description = "重新评判指定提交")
    @PostMapping("/{id}/rejudge")
    public Result<Boolean> rejudgeSubmission(@Parameter(description = "提交ID") @PathVariable String id) {
        Boolean result = submissionService.rejudgeSubmission(id);
        return Result.success(result);
    }

    @Operation(summary = "获取用户最佳提交", description = "获取用户在指定问题上的最佳提交")
    @GetMapping("/best")
    public Result<SubmissionVO> getUserBestSubmission(
            @Parameter(description = "问题ID") @RequestParam String problemId) {
        validateId(problemId, "问题ID");
        String userId = getCurrentUserId();
        SubmissionVO submission = submissionService.getUserBestSubmission(userId, problemId);
        return success(submission);
    }

    @Operation(summary = "获取问题最佳提交", description = "获取指定问题的最佳提交列表")
    @GetMapping("/problem/{problemId}/best")
    public Result<List<SubmissionVO>> getProblemBestSubmissions(
            @Parameter(description = "问题ID") @PathVariable String problemId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<SubmissionVO> submissions = submissionService.getProblemBestSubmissions(problemId, limit);
        return Result.success(submissions);
    }

    @Operation(summary = "获取最近提交", description = "获取用户最近的提交记录")
    @GetMapping("/recent")
    public Result<List<SubmissionVO>> getRecentSubmissions(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = getCurrentUserId();
        List<SubmissionVO> submissions = submissionService.getRecentSubmissions(userId, limit);
        return success(submissions);
    }

    @Operation(summary = "获取优秀提交", description = "获取公开的优秀代码提交")
    @GetMapping("/excellent")
    public Result<List<SubmissionVO>> getExcellentSubmissions(
            @Parameter(description = "问题ID") @RequestParam(required = false) String problemId,
            @Parameter(description = "编程语言") @RequestParam(required = false) String language,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<SubmissionVO> submissions = submissionService.getExcellentSubmissions(problemId, language, limit);
        return Result.success(submissions);
    }

    @Operation(summary = "分享提交", description = "分享代码提交")
    @PostMapping("/{id}/share")
    public Result<Boolean> shareSubmission(@Parameter(description = "提交ID") @PathVariable String id) {
        Boolean result = submissionService.shareSubmission(id);
        return Result.success(result);
    }

    @Operation(summary = "取消分享提交", description = "取消分享代码提交")
    @PostMapping("/{id}/unshare")
    public Result<Boolean> unshareSubmission(@Parameter(description = "提交ID") @PathVariable String id) {
        Boolean result = submissionService.unshareSubmission(id);
        return Result.success(result);
    }

    @Operation(summary = "获取提交统计", description = "获取用户提交统计信息")
    @GetMapping("/statistics")
    public Result<Object> getSubmissionStatistics(
            @Parameter(description = "开始时间") @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        String userId = getCurrentUserId();
        Object statistics = submissionService.getUserSubmissionStatistics(userId, startTime, endTime);
        return success(statistics);
    }

    @Operation(summary = "获取语言统计", description = "获取编程语言使用统计")
    @GetMapping("/statistics/languages")
    public Result<List<Object>> getLanguageStatistics(
            @Parameter(description = "开始时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        List<Object> statistics = submissionService.getLanguageStatistics(startTime, endTime);
        return Result.success(statistics);
    }

    @Operation(summary = "获取提交趋势", description = "获取提交趋势数据")
    @GetMapping("/statistics/trend")
    public Result<List<Object>> getSubmissionTrend(
            @Parameter(description = "天数") @RequestParam(defaultValue = "7") Integer days) {
        List<Object> trend = submissionService.getSubmissionTrend(days);
        return Result.success(trend);
    }

    @Operation(summary = "检测代码抄袭", description = "检测代码是否存在抄袭")
    @PostMapping("/{id}/plagiarism-check")
    public Result<Object> checkPlagiarism(@Parameter(description = "提交ID") @PathVariable String id) {
        Object result = submissionService.checkPlagiarism(id);
        return Result.success(result);
    }

    @Operation(summary = "获取相似提交", description = "获取相似的代码提交")
    @GetMapping("/{id}/similar")
    public Result<List<SubmissionVO>> getSimilarSubmissions(
            @Parameter(description = "提交ID") @PathVariable String id,
            @Parameter(description = "相似度阈值") @RequestParam(defaultValue = "0.8") Double threshold,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<SubmissionVO> submissions = submissionService.getSimilarSubmissions(id, threshold, limit);
        return Result.success(submissions);
    }

    @Operation(summary = "导出提交记录", description = "导出提交记录为Excel文件")
    @GetMapping("/export")
    public Result<String> exportSubmissions(
            @Parameter(description = "用户ID") @RequestParam(required = false) String userId,
            @Parameter(description = "问题ID") @RequestParam(required = false) String problemId,
            @Parameter(description = "编程语言") @RequestParam(required = false) String language,
            @Parameter(description = "提交状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "开始时间") @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        String downloadUrl = submissionService.exportSubmissions(userId, problemId, language, status, startTime, endTime);
        return Result.success(downloadUrl);
    }
}
